package com.ecoolex.ying.space.core.manager;

import java.sql.Date;
import java.time.Instant;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.framework.common.pojo.Page;
import com.ecoolex.framework.common.pojo.Pagination;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.StringUtil;
import com.ecoolex.ying.space.core.dao.UserInfoExtDAO;
import com.ecoolex.ying.space.entity.UserInfoExt;
import com.ecoolex.ying.space.enums.UserIdentityAuthenticationDomainType;


@Service
public class UserInfoExtManager {

    @Autowired
    private UserInfoExtDAO dao;

    public UserInfoExt getByUserId(Integer userId) {
        return dao.selectByPrimaryKey(userId);
    }

    public UserInfoExt edit(UserInfoExt record, String updateUser) {
        record.setUpdateUser(updateUser);
        record.setUpdateTime(Date.from(Instant.now()));
        dao.updateByPrimaryKeySelective(record,
            UserInfoExt.Column.excludes(UserInfoExt.Column.deleted,
                UserInfoExt.Column.createUser,
                UserInfoExt.Column.createTime));
        return record;
    }

    public void create(Integer userId, String createUser) {
        UserInfoExt record = new UserInfoExt();
        record.setUserId(userId);
        record.setDeleted(UserInfoExt.NOT_DELETED);
        record.setCreateUser(createUser);
        record.setCreateTime(Date.from(Instant.now()));
        record.setUpdateUser(createUser);
        record.setUpdateTime(Date.from(Instant.now()));
        dao.insert(record);
    }

    public Pagination<Integer> queryRecommendWatchUser(String keyword, Integer currentUserId, Page page) {
        String newKeyword;
        if (Check.notNullOrTrimEmpty(keyword)) {
            newKeyword = '%' + StringUtil.trim(keyword)
                + '%';
        } else {
            newKeyword = null;
        }
        return Pagination.create(page,
            dao.countRecommendWatchUser(newKeyword,
                currentUserId,
                UserIdentityAuthenticationDomainType.OFFICIALPLATFORM.real()),
            () -> dao.queryRecommendWatchUser(newKeyword,
                currentUserId,
                UserIdentityAuthenticationDomainType.OFFICIALPLATFORM.real(),
                page));
    }

}